package com.aishua.fire.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.Query;

//import javax.persistence.EntityManager;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aishua.fire.common.ObjectToMapUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 通用的分页查询业务接口
 * @author Administrator
 *
 */
@Slf4j
@Service
public class CommonServiceImpl<T> {

	@Autowired
    private EntityManager entityManager;
	
	
	/**
	 * 查询条件对象
	 * @param obj
	 * @return
	 */
	public List<T> searchByEqualCondition(Object obj) {
		String sql = "from "+obj.getClass().getSimpleName()+" where ";
		
//		StringBuilder jqlBuilder = new StringBuilder();
		
		Map<String, Object> conditionMap = ObjectToMapUtil.setConditionMap(obj);
		Set<Entry<String, Object>> entrySet = conditionMap.entrySet();
		for(Entry<String, Object> conditionEntry:entrySet) {
			String key = conditionEntry.getKey();
			log.info("字段名:{}",key);
			sql += key+"=:"+key;
			
		}
		Query query = this.entityManager.createQuery(sql);
		
		for(Entry<String, Object> conditionEntry:entrySet) {
			query.setParameter(conditionEntry.getKey(), conditionEntry.getValue());
		}
		
		return query.getResultList();
	}
	
	/**
	 * 查询条件对象
	 * @param obj
	 * @return
	 */
	public List<T> searchByLikeCondition(Object obj) {
		String sql = "from "+obj.getClass().getSimpleName()+" where ";
		
//		StringBuilder jqlBuilder = new StringBuilder();
		
		Map<String, Object> conditionMap = ObjectToMapUtil.setConditionMap(obj);
		Set<Entry<String, Object>> entrySet = conditionMap.entrySet();
		for(Entry<String, Object> conditionEntry:entrySet) {
			String key = conditionEntry.getKey();
			log.info("字段名:{}",key);
			sql += key+" like CONCAT('%',:"+key+",'%')";
			
		}
		Query query = this.entityManager.createQuery(sql);
		
		for(Entry<String, Object> conditionEntry:entrySet) {
			query.setParameter(conditionEntry.getKey(), conditionEntry.getValue());
		}
		
		return query.getResultList();
	}
	
}
